package com.coolw.data.migrate.common.task;

import com.coolw.data.migrate.common.alarm.Alarm;
import com.coolw.data.migrate.common.alarm.AlarmStatusEnum;
import com.coolw.data.migrate.entity.DataMigrateLogEntity;
import com.coolw.data.migrate.service.DataMigrateLogService;
import org.dromara.hutool.core.collection.CollUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 告警监控任务
 *
 * @author coolw
 * @date 2024/2/21 15:29
 */
@Component
public class AlarmMonitorTask {

    @Resource
    private Alarm emailAlarm;

    @Resource
    private DataMigrateLogService dataMigrateLogService;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void alarm() {
        List<DataMigrateLogEntity> records = dataMigrateLogService.scanNeedAlarmList();
        if (CollUtil.isEmpty(records)) {
            return;
        }

        // 告警次数+1
        records.forEach(r -> r.setAlarmCount(r.getAlarmCount() + 1));

        boolean result = emailAlarm.doAlarm(records);

        for (DataMigrateLogEntity record : records) {
            AlarmStatusEnum alarmStatusEnum = result ? AlarmStatusEnum.ALREADY_ALARM : AlarmStatusEnum.ALARM_FAIL;

            // 更新告警状态和计数
            dataMigrateLogService.updateAlarmStatusAndCount(record.getId(), alarmStatusEnum, record.getAlarmCount());
        }
    }
}
